#include "globals.h"

#define Tileset 0
#define BG 1



wndBGImport::wndBGImport(){
}

wndBGImport::~wndBGImport(){

}


BOOL CALLBACK BGiProc(HWND hwnd,UINT message,WPARAM wParam,LPARAM lParam)
{
	HDC hdc;
	PAINTSTRUCT ps;
	int i=0;
	char  str[16][4]={"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
	char  FileStuff[1024]={0};
	switch (message)
	{
		
		case WM_INITDIALOG: 
			BGi.me=hwnd;
			BGi.picloaded=0;
			BGi.cboPal.Init(GetDlgItem(hwnd,cboBGPalette));
			for(i=0;i<16;i++){
			    BGi.cboPal.Additem(str[i]);
			}
			    BGi.cboPal.SetListIndex(8);
			
			break;
        case WM_COMMAND:
            switch(LOWORD(wParam)){
            case cmdTS:

	           if(BGi.picloaded){
				   BGi.Type = Tileset;
            // sprintf(BGi.FileString,"D:\\Documents and Settings\\Matt\\Desktop\\Romhacking\\tiles.png");
				 BGi.MakeFiles();
				 BGi.LoadFiles();
				 BGi.DelFiles();
				 BGi.Draw();
				}

				break;
			case cmdBG:
				if(BGi.picloaded){
				BGi.Type=BG;
            // sprintf(BGi.FileString,"D:\\Documents and Settings\\Matt\\Desktop\\Romhacking\\tiles.png");
				 BGi.MakeFiles();
				 BGi.LoadFiles();
				 BGi.DelFiles();
				 BGi.Draw();
				}
				break;
          
			case cmdSelFile:
				if(GBA.ReturnFileName("Please Select a file\0*.*\0",FileStuff,1024)){
                     sprintf(BGi.FileString,"%s",FileStuff);
					 for(i =strlen(FileStuff);i>0;i--){
                        if(FileStuff[i]==0x5C){
                            break;


						}
                      

					 }
                    SetWindowText(GetDlgItem(hwnd,lblFileName),&FileStuff[i+1]);
					BGi.picloaded=1;
				}
				
				break;

            case cboBGPalette:
				   if(HIWORD(wParam) == CBN_SELCHANGE){
					   BGi.palpos=(u8)BGi.cboPal.GetListIndex();
				   }
					   break;
			case cmdSave:
				switch(BGi.Type){
				case Tileset:
					BGi.SaveCustTileset();
					break;
				case BG:
					BGi.SaveCustBGROM();
					break;
					
					
					
				}
				   break;
			case WM_DESTROY:
					 ShowWindow(hwnd, SW_HIDE);
				break;	
			}
			break;
	    case WM_PAINT:
		hdc = BeginPaint(hwnd, &ps);
		
		BGi.Pic.Blit(hdc, 15,23,BGi.pW*8,BGi.pH*8,0,0);
        //DrawTileRect(hdc,mpSTS,8);
		EndPaint(hwnd, &ps);
		break;

	}
		return 0;
}

int wndBGImport::SaveCustBGROM(){

int radarray[3]={rdo0,rdo1,rdo2};
u32 offsets[4]={0};//4 Offsets
u32 csize=0;
u16 filler=0;
char stroff[10]={0};
u8  tempbuff[32967]={0};
u32 i = 0;
if(tilesize> 0x7DE0 || ((((0x7DE0)-tilesize)/32) >= 1024)){

	MessageBox(me,"Cannot save to ROM, this image has too many non repeating tiles\nPlease choose a different image","Error",MB_OK);
	return 0;
}
u16 ntsz=(u16)((0x7DE0)-tilesize)/32;
//Figure out palsize
for(i=0; i<256;i++){
		if(GPal[i]==0 && GPal[i+1]==0 && GPal[i+2]==0)  {
 
			 palsize = (u16)i;
			 break;
			}

}
//Compress palette
csize=GBA.LZ77Comp(palsize*2, (u8*)GPal, tempbuff);
//for(i=0;i<palsize;i++){
//GPal[palpos<<5+i]=GPal[i];
//}
palpos= (u8)cboPal.GetListIndex();
offsets[1]=GBA.FindFreeSpace(csize,0xFF);
fseek(GBA.ROM,offsets[1],SEEK_SET);
fwrite(tempbuff,1,csize,GBA.ROM);
memset(tempbuff,0,32967);
GBA.Reopen();
//Convert Buffer to use the pal

csize=GBA.LZ77Comp(tilesize, (u8*)buffer, tempbuff);
offsets[3]=GBA.FindFreeSpace(csize,0xFF);
fseek(GBA.ROM,offsets[3],SEEK_SET);
fwrite(tempbuff,1,csize,GBA.ROM);
memset(tempbuff,0,32967);
GBA.Reopen();






//Left Will the position and right will be the size of the palette
           //top will be starting point of tiles in RAM

/*map.left  = palpos * 16;
map.right = palsize+map.left;
map.top   = ntsz;
MakeFiles(1);
LoadFiles(1);
ft = fopen("map1.bin", "w+b");
if(ft){
	fwrite(tilemap,1,mapsize*2,ft);
	fclose(ft);
}*/
for(i=0;i<mapsize;i++) {
  	tilemap[i] +=(palpos<<0xc)+ntsz;
}
/*ft = fopen("map2.bin", "w+b");
if(ft){
	fwrite(tilemap,1,mapsize*2,ft);
	fclose(ft);
}*/
csize=GBA.LZ77Comp(mapsize*2, (u8*)tilemap, tempbuff);
offsets[2]=GBA.FindFreeSpace(csize,0xFF);
fseek(GBA.ROM,offsets[2],SEEK_SET);
fwrite(tempbuff,1,csize,GBA.ROM);


GBA.Reopen();
for(i=0;i<3;i++){ //Choses i val
		if(	SendMessage(GetDlgItem(me,radarray[i]),BM_GETCHECK,0,0)==BST_CHECKED)
                	break;
}

offsets[0]=GBA.FindFreeSpace(3*4+2,0xFF);
fseek(GBA.ROM,offsets[0],SEEK_SET);
fwrite(&i,1,1,GBA.ROM);
i=cboPal.GetListIndex();
fwrite(&i,1,1,GBA.ROM);
fwrite(&filler,2,1,GBA.ROM);
for(i = 1;i<4;i++) offsets[i]+=0x8000000;


sprintf(stroff, "%X", offsets[0]);	 
SetWindowText(GetDlgItem(hwndHeader,txtBIO), stroff);
for(i=1;i<4;i++)
fwrite(&offsets[i],1,4,GBA.ROM);
import = 1;
SaveHeader(0);
GetCBG();
DrawRoom();
	return 0;
}
int wndBGImport::MakeFiles(){
    char gritpath[1024]={0};
	char param[2048]={0};
	int  retval=0;

	int  i=0;
	
	char radiostring[3][32]={"-Ah 32 -Aw 32","-Mh 64 -Aw 32","-Ah 32 -Aw 64"};
	int  psz[3][2]={  {32,32}, {64,32}, {32,64}};
	int radarray[3]={rdo0,rdo1,rdo2};
	for(retval=strlen(FileString);retval>0;retval--) 
		     if(FileString[retval] == 0x5c)
					break; 

	sprintf(picname,"%s",&FileString[retval+1]);
	sprintf(param,"%s\\%s",AppPath,picname);
    CopyFile(FileString,param,retval);
	sprintf(gritpath,"%s\\grit.exe",AppPath);    
	for(i=0;i<3;i++){ //Choses i val
		if(	SendMessage(GetDlgItem(me,radarray[i]),BM_GETCHECK,0,0)==BST_CHECKED)
                	break;
	}
		pW=psz[i][0];
		pH=psz[i][1];

		
	sprintf(param,"%s -gt -gu 8 -gB4 -mLs -MRp -mRtpf -ft bin %s",picname,radiostring[i]);

    //We have the location of grit, and the parameter to call
	//So Call it
	ShellExecute( 0, "open", gritpath, param, AppPath, 1);
	Sleep(5000);
	//MakeFiles is done!

	return 0;
}
int wndBGImport::LoadFiles(){
//Now we make sure all of our files exist
//Should have about 4 files 

#define header  0
#define img     1
#define pal     2
#define map     3
int i=0,j=0;
char name[1024]={0};
char Files[4][1024]={0};
char FileTypes[4][16]={".h",".img.bin",".pal.bin",".map.bin"};
FILE* fp=NULL;
sprintf(name,"%s",picname);
for(i=strlen(picname);i>0;i--){
	if(name[i]=='.'){
	 name[i]=0;
	 break;
	}
	name[i]=0;


}
//have base name now let's fill out Files
for(i=0;i<4;i++)
	sprintf(Files[i], "%s\\%s%s",AppPath,name,FileTypes[i]);
for(i=0;i<3;i++){
j=i+1;
fp=fopen(Files[j],"r+b");
	if(!fp){
		sprintf(name,"File %s\n Could not be found aborting importation",Files[j]);
		MessageBox(0,name,"Error",MB_OK);
		for(i=0;i<4;i++)   DeleteFile(Files[i]);
		sprintf(Files[0],"%s\\%s",AppPath,name);
		DeleteFile(Files[0]);
		return 0;
	}else{
		fseek(fp,0,SEEK_SET);
		switch(j){
			case img:
			
					tilesize=GBA.ReturnEOF(fp);
					fseek(fp,0,SEEK_SET);
					fread(buffer,1,tilesize,fp);
			
				
				break;
			case  pal:
				
					palsize=GBA.ReturnEOF(fp)/2;
					fseek(fp,0,SEEK_SET);
					fread(GPal,2,palsize,fp);
			
				break;

			case map:
				mapsize=GBA.ReturnEOF(fp)/2;
				fseek(fp,0,SEEK_SET);
			    
				if(BGi.Type==Tileset){
				  fread(&tilemap[164],2,mapsize,fp);
				}else{
                  fread(tilemap,2,mapsize,fp);
				}
			
				break;



		}

	}
	fclose(fp);
}

for(i=0;i<4;i++){  
	DeleteFile(Files[i]);
	sprintf(Files[0],"%s\\%s",AppPath,name);
	DeleteFile(Files[0]);
//Everything should be loaded
}
return 0;
}

int wndBGImport::DelFiles(){
//We don't need any of the newly created files everything is in memory :)
//DeleteFile(picname);//That all we do here? wtf


	return 0;
}

int wndBGImport::Draw(){
    int rex, rey,i , x, y, scrX, scrY;
	rex=rey=i=x=y=scrX=scrY=0;//
	Tiles.Load(buffer,tilesize/32);
	GBA.DecodePal(GPal,PCPal,palsize/16, 0) ; 
    Pic.Create(pW*8,pH*8);
	Pic.SetPalette(PCPal);
    //mX=pW;
	//mY=pH;
	//rex = (mX == 64 ? 2 :  1);
	//rey = (mY == 64 ? 2 :  1);
		
	//	for(scrY = 0; scrY < pH/32; scrY++)
	//	{	
	//		for(scrX = 0; scrX < pW/32; scrX++)
	//		{
				for(y = 0; y < pH; ++y)
				{
					for(x = 0; x < pW; ++x)
					{
						// Pic.Draw(Tiles,x*8 + scrX*256	,y*8+ scrY*256 ,  tilemap[i]);
						Pic.Draw(Tiles,x*8 	,y*8 ,  tilemap[i]);
						i++;
					}
				}
		//	}
	//	}
	InvalidateRect(me,0,1);
	return 0;
}


int wndBGImport::SaveCustTileset(){


u32 offsets[4]={0};//4 Offsets
u32 csize=0;


u8  tempbuff[32967]={0};
u32 i = 0;
if(((tilesize)/32) >= 0x286){

	MessageBox(me,"Cannot save to ROM, this image has too many non repeated tiles\nPlease choose a different image","Error",MB_OK);
	return 0;
}
u16 ntsz=(u16)(tilesize)/32;
//Just copy 16*6 colors. 
//palpos= (u8)cboPal.GetListIndex();
offsets[1]=GBA.FindFreeSpace(192 ,0xFF);
fseek(GBA.ROM,offsets[1],SEEK_SET);
fwrite(tempbuff,1,csize,GBA.ROM);
memset(tempbuff,0,32967);
GBA.Reopen();
//Convert Buffer to use the pal

csize=GBA.LZ77Comp(tilesize, (u8*)buffer, tempbuff);
offsets[3]=GBA.FindFreeSpace(csize,0xFF);
fseek(GBA.ROM,offsets[3],SEEK_SET);
fwrite(tempbuff,1,csize,GBA.ROM);
memset(tempbuff,0,32967);
GBA.Reopen();






//Left Will the position and right will be the size of the palette
           //top will be starting point of tiles in RAM

/*map.left  = palpos * 16;
map.right = palsize+map.left;
map.top   = ntsz;
MakeFiles(1);
LoadFiles(1);
ft = fopen("map1.bin", "w+b");
if(ft){
	fwrite(tilemap,1,mapsize*2,ft);
	fclose(ft);
}*/
for(i=0;i<mapsize;i++) {
  	tilemap[i] +=(palpos<<0xc)+ntsz;
}
/*ft = fopen("map2.bin", "w+b");
if(ft){
	fwrite(tilemap,1,mapsize*2,ft);
	fclose(ft);
}*/
//FillOutArray(tilemap);
//csize=GBA.LZ77Comp(mapsize*2, (u8*)tilemap, tempbuff);
offsets[2]=GBA.FindFreeSpace(csize,0xFF);
fseek(GBA.ROM,offsets[2],SEEK_SET);
fwrite(tempbuff,1,csize,GBA.ROM);


GBA.Reopen();
/*
offsets[0]=GBA.FindFreeSpace(3*4+2,0xFF);
fseek(GBA.ROM,offsets[0],SEEK_SET);
fwrite(&i,1,1,GBA.ROM);
i=cboPal.GetListIndex();
fwrite(&i,1,1,GBA.ROM);
fwrite(&filler,2,1,GBA.ROM);
for(i = 1;i<4;i++) offsets[i]+=0x8000000;


sprintf(stroff, "%X", offsets[0]);	 
SetWindowText(GetDlgItem(hwndHeader,txtBIO), stroff);
for(i=1;i<4;i++)
fwrite(&offsets[i],1,4,GBA.ROM);
import = 1;*/
GameEngine->Members.RoomTilesets[Tileset].gTiles=offsets[3] + 0x8000000;
//NOT FINISHED.
SaveHeader(0);
//GetTileset();
DrawRoom();
	return 0;
}


int wndBGImport::FillOutArray(u8* array){
	unsigned char rawData[328] =
{
    0x02, 0x00, 0x40, 0x00, 0x40, 0x00, 0x40, 0x00, 0x40, 0x00, 0x59, 0x14, 0x59, 0x14, 0x79, 0x14, 
    0x79, 0x14, 0x59, 0x10, 0x59, 0x10, 0x79, 0x10, 0x79, 0x10, 0x59, 0x14, 0x59, 0x10, 0x79, 0x14, 
    0x79, 0x10, 0x40, 0x00, 0x5A, 0x14, 0x40, 0x00, 0x7A, 0x14, 0x5A, 0x10, 0x40, 0x04, 0x7A, 0x10, 
    0x40, 0x04, 0x5B, 0x14, 0x5A, 0x14, 0x7B, 0x14, 0x7A, 0x14, 0x5A, 0x10, 0x5B, 0x10, 0x7A, 0x10, 
    0x7B, 0x10, 0x5C, 0x14, 0x5A, 0x14, 0x7C, 0x14, 0x7A, 0x14, 0x5A, 0x10, 0x5C, 0x10, 0x7A, 0x10, 
    0x7C, 0x10, 0x5D, 0x14, 0x5A, 0x14, 0x7D, 0x14, 0x7A, 0x14, 0x5A, 0x10, 0x5D, 0x10, 0x7A, 0x10, 
    0x7D, 0x10, 0x5E, 0x14, 0x5A, 0x14, 0x7E, 0x14, 0x7A, 0x14, 0x5A, 0x10, 0x5E, 0x10, 0x7A, 0x10, 
    0x7E, 0x10, 0x5F, 0x14, 0x5A, 0x14, 0x7F, 0x14, 0x7A, 0x14, 0x5A, 0x10, 0x5F, 0x10, 0x7A, 0x10, 
    0x7F, 0x10, 0x40, 0x00, 0x40, 0x00, 0x40, 0x00, 0x40, 0x00, 0x99, 0x14, 0x98, 0x14, 0xB9, 0x14, 
    0xB8, 0x14, 0x98, 0x10, 0x99, 0x10, 0xB8, 0x10, 0xB9, 0x10, 0x98, 0x14, 0x98, 0x10, 0xB8, 0x14, 
    0xB8, 0x10, 0x40, 0x00, 0x9A, 0x14, 0x40, 0x00, 0xBA, 0x14, 0x9A, 0x10, 0x40, 0x04, 0xBA, 0x10, 
    0x40, 0x04, 0x9B, 0x14, 0x9A, 0x14, 0xBB, 0x14, 0xBA, 0x14, 0x9A, 0x10, 0x9B, 0x10, 0xBA, 0x10, 
    0xBB, 0x10, 0x9C, 0x14, 0x9A, 0x14, 0xBC, 0x14, 0xBA, 0x14, 0x9A, 0x10, 0x9C, 0x10, 0xBA, 0x10, 
    0xBC, 0x10, 0x9D, 0x14, 0x9A, 0x14, 0xBD, 0x14, 0xBA, 0x14, 0x9A, 0x10, 0x9D, 0x10, 0xBA, 0x10, 
    0xBD, 0x10, 0x9E, 0x14, 0x9A, 0x14, 0xBE, 0x14, 0xBA, 0x14, 0x9A, 0x10, 0x9E, 0x10, 0xBA, 0x10, 
    0xBE, 0x10, 0x9F, 0x14, 0x9A, 0x14, 0xBF, 0x14, 0xBA, 0x14, 0x9A, 0x10, 0x9F, 0x10, 0xBA, 0x10, 
    0xBF, 0x10, 0x40, 0x00, 0x40, 0x00, 0x40, 0x00, 0x40, 0x00, 0xB9, 0x1C, 0xB8, 0x1C, 0x99, 0x1C, 
    0x98, 0x1C, 0xB8, 0x18, 0xB9, 0x18, 0x98, 0x18, 0x99, 0x18, 0xB8, 0x1C, 0xB8, 0x18, 0x98, 0x1C, 
    0x98, 0x18, 0x40, 0x08, 0xBA, 0x1C, 0x40, 0x08, 0x9A, 0x1C, 0xBA, 0x18, 0x40, 0x0C, 0x9A, 0x18, 
    0x40, 0x0C, 0xBB, 0x1C, 0xBA, 0x1C, 0x9B, 0x1C, 0x9A, 0x1C, 0xBA, 0x18, 0xBB, 0x18, 0x9A, 0x18, 
    0x9B, 0x18, 0xBC, 0x1C, 0xBA, 0x1C, 0x9C, 0x1C, 
} ;
memcpy(array, rawData, 328);
return 0;
}